//
//  JQFYCreatGroupViewController.m
//  JQFY
//
//  Created by apple on 2017/10/9.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYCreatGroupViewController.h"
#import "JQFYCreatGroupCoverTableViewCell.h"
#import "JQFYCreatGroupInfoTableViewCell.h"
#import "JQFYCreatGroupFlockInfoTableViewCell.h"
#import "JQFYGroupDataModel.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "JQFYMessageViewController.h"

typedef NS_ENUM(NSInteger, JQFYCreatGroupSectionType) {
    JQFYCreatGroupSectionTypeCover,
    JQFYCreatGroupSectionTypeGroupInfo,
    JQFYCreatGroupSectionTypeFlockInfo
};
typedef void(^GroupData)(void);
@interface JQFYCreatGroupViewController ()<
UITableViewDelegate,
UITableViewDataSource,
CreatGroupDelegate,
JQFYCreatGroupInfoTableViewCellDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
TZImagePickerControllerDelegate
>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray<NSNumber *> *sectionArray;
@property (nonatomic, strong) JQFYCreatGroupModel *model;
@property (nonatomic ,strong) JQFYGroupDataModel *groupDataModel;
//创建群参数
@property (nonatomic ,strong) NSData *group_head;
@property (nonatomic ,copy) NSString *group_name;
@property (nonatomic ,copy) NSString *owner_user;
//@property (nonatomic ,copy) NSString *description;//群描述
@property (nonatomic ,copy) NSString *max_users;
@property (nonatomic ,copy) NSString *activeid;

@end

@implementation JQFYCreatGroupViewController

- (NSArray<NSNumber *> *)sectionArray {
    return @[@(JQFYCreatGroupSectionTypeCover),
             @(JQFYCreatGroupSectionTypeGroupInfo),
             @(JQFYCreatGroupSectionTypeFlockInfo)];
}
-(void)setupNav{
    
    self.navigationItem.title = @"创建群";
    UIFont *font = [UIFont fontWithName:@"Verdana-Bold" size:17];
    NSDictionary *dic = @{NSFontAttributeName:font,
                          NSForegroundColorAttributeName: [UIColor whiteColor]};
    self.navigationController.navigationBar.titleTextAttributes =dic;
    UIImage *leftImg = [UIImage imageNamed:@"ticketInfo_back"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImg style:UIBarButtonItemStylePlain target:self action:@selector(didClickBack)];
}

- (void)setupUI {
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    [self.view addGestureRecognizer:tapGestureRecognizer];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 67, 0);
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[JQFYCreatGroupCoverTableViewCell class] forCellReuseIdentifier:@"JQFYCreatGroupCoverTableViewCell"];
    [_tableView registerClass:[JQFYCreatGroupInfoTableViewCell class] forCellReuseIdentifier:@"JQFYCreatGroupInfoTableViewCell"];
    [_tableView registerClass:[JQFYCreatGroupFlockInfoTableViewCell class] forCellReuseIdentifier:@"JQFYCreatGroupFlockInfoTableViewCell"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupNav];
}

#pragma mark - UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    JQFYCreatGroupSectionType type = self.sectionArray[indexPath.row].integerValue;
    switch (type) {
        case JQFYCreatGroupSectionTypeCover: {
            return [JQFYCreatGroupCoverTableViewCell heigtForCell];
        }
            break;
        case JQFYCreatGroupSectionTypeGroupInfo: {
            return [JQFYCreatGroupInfoTableViewCell heigtForCell];
        }
            break;
        case JQFYCreatGroupSectionTypeFlockInfo: {
            return [JQFYCreatGroupFlockInfoTableViewCell heigtForCell];
        }
            break;
        default:
            break;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sectionArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JQFYCreatGroupSectionType type = self.sectionArray[indexPath.row].integerValue;
    switch (type) {
        case JQFYCreatGroupSectionTypeCover: {
            JQFYCreatGroupCoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JQFYCreatGroupCoverTableViewCell" forIndexPath:indexPath];
            cell.creatGroupModel = self.model;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case JQFYCreatGroupSectionTypeGroupInfo: {
            JQFYCreatGroupInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JQFYCreatGroupInfoTableViewCell" forIndexPath:indexPath];
            cell.creatGroupModel = self.model;
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case JQFYCreatGroupSectionTypeFlockInfo: {
            JQFYCreatGroupFlockInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JQFYCreatGroupFlockInfoTableViewCell" forIndexPath:indexPath];
            cell.creatGroupModel = self.model;
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        default:
            break;
    }
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"erroeCell"];
    return [tableView dequeueReusableCellWithIdentifier:@"errorCell" forIndexPath:indexPath];
}
#pragma mark -
#pragma mark 点击事件
//点击确认推出控制器
-(void)didCreatGroup
{
    NSLog(@"点击确认推出控制器")
    if (self.model.groupName&&self.model.constraints[self.model.selectedIndex].maxCount&&self.group_head) {
        [self uploadImage:^{
//            JQFYMessageViewController *chatController = [[JQFYMessageViewController alloc] initWithConversationChatter:self.groupDataModel.group_easemob_id conversationType:EMConversationTypeGroupChat];
//            chatController.groupDataModel = self.groupDataModel;
//            [self.navigationController pushViewController:chatController animated:YES];
        } and:^{
            [MBProgressHUD showWithMessage:@"网络不好请稍后再试"];
        }];
    }else{
        [MBProgressHUD showWithMessage:@"请填写完整的信息"];
    }
}
- (void)uploadImage :(GroupData)success and:(GroupData)faliure{
    JQFYImageModel *imageModel = self.model.constraints[self.model.selectedIndex];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *dict = @{
                           @"group_name":self.model.groupName,//群名
                           @"owner_user":[JQFYUserData userDataInSandbox].loginName,//群主名 用户名
                           @"description":@"uninhibited night",//群简介
                           @"max_users":imageModel.maxCount,//最大人数
                           @"activeid":self.Listmodel.id,//活动ID
                           @"token":[JQFYUserData userDataInSandbox].token//token
                           };
    [manager POST:@"http://app.uninhibited.cn/api/easemob/group/add" parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:self.group_head name:@"group_head" fileName:fileName mimeType:@"image/png"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *msg = responseObject[@"msg"];
        self.groupDataModel = [JQFYGroupDataModel yy_modelWithDictionary:msg];
        NSLog(@"上传成功 ---%@--解析----%@",responseObject,_groupDataModel);
        success();
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        faliure();
        NSLog(@"上传失败 %@", error);
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self.view endEditing:YES];
}

//点击返回键
-(void)didClickBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(JQFYCreatGroupModel *)model{
    if (!_model) {
        _model = [[JQFYCreatGroupModel alloc] init];
        _model.address = self.Listmodel.tickets_address;
    }
    return _model;
}
//点击选择图片取消按钮所执行的方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
//点击选择照片代理实现
- (void)didSelectedCoverImage:(UIButton *)button{
    //弹出相册选择保存并回调照片
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    imagePickerVc.maxImagesCount = 1;
    imagePickerVc.naviBgColor = [UIColor colorWithHex:0x694CE6];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        NSData *imageData = UIImagePNGRepresentation(photos[0]);
        self.group_head = imageData;
        [button setImage:photos[0] forState:UIControlStateNormal];
        if (self.iconImageBlock) {
            self.iconImageBlock(photos[0]);
        }
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


@end
